<template>
  <div class="bad-registration-detail">
    <n-card v-if="loading" :bordered="false" class="proCard">
      <n-spin :show="loading" class="loading" />
    </n-card>

    <DFPageDetail v-else :page-options="pageOptions" />
  </div>
</template>

<script lang="ts" setup name="BadRegistrationDetail">
  import lang from '../lang';
  import { useMixins } from '@/hooks/useMixins';
  import {
    addBadRegistration,
    badRegistrationInfo,
    updateBadRegistration,
  } from '@/api/wip/badRegistration';
  import { listBad } from '@/api/base/bad';
  import { listOrder } from '@/api/production/order';
  import { generateRandomValue } from '@/utils/index';
  import { dateFn } from '@/utils/http/axios/ipcIndex';
  import { listMachine } from '@/api/base/machine';
  import { listShift } from '@/api/base/shift';

  const { t, loadLangFn, routerType, getDictDataListFn, message } = useMixins();

  const loading = ref(false);

  const badList = ref([]);

  const machineList = ref([]);

  const orderCodeList = ref([]);

  const shiftList = ref([]);

  const badLevelList = ref([]);

  loadLangFn(lang);

  // const handleEditDataFn = (res: any = {}) => {
  //   console.log(res);
  //     return res;
  //   };

  async function initFn() {
    try {
      if (routerType !== 'check') {
        loading.value = true;

        const res = await Promise.all([
          listBad(),
          listOrder({
            orderStatusCodeList: ['30', '40', '60'],
          }),
          listMachine(),
          listShift(),
          getDictDataListFn('bad_level'),
        ]);

        const [list1, list2, list3, list4, list5] = res;

        // console.log(list1)

        badList.value = list1.data.map((item) => ({
          ...item,
          label: item.badName,
          value: item.badCode,
        }));

        orderCodeList.value = list2.data || [];

        machineList.value =
          list3?.data.map((item) => ({
            label: item.machineName,
            value: item.machineCode,
          })) || [];

        shiftList.value =
          list4?.data.map((item) => ({
            label: item.shiftName,
            value: item.shiftCode,
            userList: item.userList,
          })) || [];

        badLevelList.value = list5;

        loading.value = false;

        // setTimeout(() => {
        //   loading.value = false;
        // }, 000);
      }
    } catch (_e) {
      // console.log(_e);
    }
  }

  const pageOptions = {
    list: [
      {
        type: 'form',
        formSchemas: [
          {
            label: 'badRegistrationCode',
            disabled: true,
          },
          {
            label: 'orderCode',
            editDisabled: true,
            component: 'NSelect',
            options: orderCodeList,
            required: true,
            componentProps: {
              labelField: 'orderCode',
              valueField: 'orderCode',
              onUpdateValue(_v: string, option: any, updateFormModelFn: any) {
                if (option) {
                  const {
                    materialLength,
                    materialWidth,
                    materialHeight,
                    scheduledEndTime,
                    scheduledStartTime,
                    machineCode,
                  } = option;
                  if (typeof updateFormModelFn === 'function') {
                    const machineName =
                      machineList.value.find((item) => item.value === machineCode)?.label || null;

                    updateFormModelFn({
                      ...option,
                      materialStandards: `${materialLength}*${materialWidth}*${materialHeight}`,
                      scheduledEndTime: scheduledEndTime
                        ? dateFn(new Date(scheduledEndTime))
                        : null,
                      scheduledStartTime: scheduledStartTime
                        ? dateFn(new Date(scheduledStartTime))
                        : null,
                      machineName,
                    });
                  }
                } else {
                  typeof updateFormModelFn === 'function' &&
                    updateFormModelFn({
                      materialCode: null,
                      materialName: null,
                      version: null,
                      materialStandards: null,
                      customName: null,
                      scheduledStartTime: null,
                      scheduledEndTime: null,
                      machineName: null,
                      materialLength: null,
                      materialWidth: null,
                      materialHeight: null,
                    });
                }
              },
            },
          },
          {
            label: 'materialCode',
            disabled: true,
          },
          {
            label: 'materialName',
            disabled: true,
          },
          {
            label: 'version',
            disabled: true,
          },
          {
            label: 'materialStandards',
            disabled: true,
          },
          {
            label: 'customName',
            disabled: true,
          },
          {
            label: 'orderNum',
            disabled: true,
            component: 'NInputNumber',
          },
          {
            label: 'scheduledStartTime',
            disabled: true,
          },
          {
            label: 'scheduledEndTime',
            disabled: true,
          },
          {
            label: 'machineName',
            disabled: true,
          },
          {
            label: 'shiftName',
            prop: 'shiftCode',
            required: true,
            component: 'NSelect',
            options: shiftList,
            componentProps: {
              filterable: true,
              tag: true,
              'on-create': (label: string) => {
                return { label, value: generateRandomValue(16), badLevelCode: '10' };
              },
              onUpdateValue(_v: string, option: any, updateFormModelFn: any) {
                if (option) {
                  if (typeof updateFormModelFn === 'function') {
                    const { label, value } = option;

                    updateFormModelFn({
                      shiftName: label,
                      shiftCode: value,
                    });
                  }
                } else {
                  typeof updateFormModelFn === 'function' &&
                    updateFormModelFn({
                      shiftName: null,
                      shiftCode: null,
                    });
                }
              },
            },
          },
          {
            label: 'remark',
            type: 'textarea',
            common: true,
            giProps: { span: 3 },
            componentProps: {
              'show-count': true,
            },
          },
        ],
      },
      {
        title: t('badRegistration.table.tableName'),
        type: 'table',
        hasSelection: true,
        ref: 'badRegistrationList',
        columns: [
          // {
          //   label: 'badName',
          //   required: true,
          //   itemData: {
          //     maxlength: 20,
          //     component: 'NSelect',
          //     options: badList,
          //   },
          // },
          {
            label: 'badName',
            required: true,
            itemData: {
              maxlength: 20,
              component: 'NSelect',
              options: badList,
              componentProps: {
                filterable: true,
                tag: true,
                'on-create': (label: string) => {
                  return { label, value: generateRandomValue(16), badLevelCode: '10' };
                },
                onUpdateValue(_v: string, option: any, updateFormModelFn: any) {
                  if (option) {
                    if (typeof updateFormModelFn === 'function') {
                      const { badLevelCode, label, value } = option;

                      const badLevelName =
                        badLevelList.value.find((item) => item.value === badLevelCode)?.label ||
                        '-';

                      updateFormModelFn({
                        badCode: value,
                        badName: label,
                        badLevelCode,
                        badLevelName,
                      });
                    }
                  } else {
                    typeof updateFormModelFn === 'function' &&
                      updateFormModelFn({
                        badCode: null,
                        badLevelCode: null,
                        badName: null,
                        badLevelName: null,
                      });
                  }
                },
              },
            },
          },
          {
            label: 'badCode',
          },
          {
            label: 'badLevelName',
          },
          {
            label: 'badNum',
            required: true,
            itemData: {
              min: 1,
              precision: 0,
              component: 'NInputNumber',
            },
          },
          {
            label: 'remark',
            common: true,
            itemData: {
              maxlength: 250,
            },
          },
        ],
      },
    ],
    formLabelWidthEn: 100,
    descriptionsListLabelWidthEn: 150,
    routeName: 'badRegistration',
    addDataFn: addBadRegistration,
    updateDataFn: updateBadRegistration,
    getDataFn: badRegistrationInfo,
    beforeSubmitFn: (data) => {
      if (data) {
        const { badRegistrationList } = data;

        if (badRegistrationList && badRegistrationList.length) {
          const obj = {};

          const isSubmit = badRegistrationList.every((item) => {
            const { badCode, badName } = item;

            if (obj[badName]) {
              return false;
            } else {
              obj[badName] = badCode;
            }

            return true;
          });

          if (!isSubmit) {
            message.error(t('badRegistration.tips.sameBadRegistration'));

            return false;
          }
        }
      }

      return true;
    },
    setSubmitDataFn: (data) => {
      if (data) {
        const { scheduledStartTime, scheduledEndTime } = data;

        data['scheduledStartTime'] = scheduledStartTime
          ? new Date(scheduledStartTime).getTime()
          : null;

        data['scheduledEndTime'] = scheduledEndTime ? new Date(scheduledEndTime).getTime() : null;
      }

      return data;
    },
    handleEditDataFn: (res) => {
      const { data } = res;

      if (data) {
        const {
          materialLength,
          materialWidth,
          materialHeight,
          scheduledStartTime,
          scheduledEndTime,
          machineCode,
          badRegistrationList,
        } = data;

        const machineName =
          machineList.value.find((item) => item.value === machineCode)?.label || null;

        data['scheduledStartTime'] = scheduledStartTime
          ? dateFn(new Date(scheduledStartTime))
          : null;

        data['scheduledEndTime'] = scheduledEndTime ? dateFn(new Date(scheduledEndTime)) : null;

        data['materialStandards'] = `${materialLength}*${materialWidth}*${materialHeight}`;

        data['machineName'] = machineName;

        data['badRegistrationList'] = badRegistrationList.map((item) => {
          return {
            ...item,
            badLevelName:
              badLevelList.value.find((bItem) => bItem.value === item.badLevelCode)?.label || null,
          };
        });
      }

      return data;
    },
    // handleEditDataFn,
  };

  initFn();
</script>

<style lang="less" scoped>
  .bad-registration-detail {
    position: relative;

    .loading {
      width: 100%;
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
  }
</style>
